package controllers;

import entities.Statement;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import entities.Categories;
import entities.Merchants;
import java.io.IOException;
import java.util.logging.Level;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import session.StatementFacade;

import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
import session.CategoriesFacade;
import session.MerchantsFacade;
import workers.MerchantsWorker;
import workers.MerchantsWorkerImpl;
import workers.statements.StatementLoader;
import workers.statements.StatementLoaderImpl;
import workers.statements.beans.CCStatementCSV;

@ManagedBean(name = "statementByMerchantController")
@SessionScoped
//@Stateless
/**
 * Controller specifically for listing statements by merchant.
 */
public class StatementByMerchantController implements Serializable {

    Logger logger = Logger.getLogger(StatementByMerchantController.class);
    //String merchantId = null;
    private Statement currentStatement;
    private Merchants currentMerchant;
    List<Merchants> currentMerchants;
    private DataModel items = null;
    @EJB
    private StatementFacade ejbStatementFacade;
    @EJB
    private MerchantsFacade ejbMerchantsFacade;
    @EJB
    private CategoriesFacade ejbCategoriesFacade;
    @EJB
    private MerchantsWorker merchantsWorker;
    @EJB
    private StatementLoader statementLoader;
    @Resource
    private UserTransaction utx;
    //@PersistenceContext(unitName = "wtfcc00PU")
    //EntityManager entityManager;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private int totalCost;

    public StatementByMerchantController() {
    }

    public Statement getCurrentStatement() {
        if (currentStatement == null) {
            currentStatement = new Statement();
            selectedItemIndex = -1;
        }
        return currentStatement;
    }

    private void setCurrentStatement(Statement current) {
        currentStatement = current;
    }

    private StatementFacade getFacade() {
        return ejbStatementFacade;
    }

    public Merchants getCurrentMerchant() {
        if (currentMerchant == null) {
            currentMerchant = new Merchants();
            selectedItemIndex = -1;
        }
        System.out.println("StatementByMerchantController / getCurrentMerchant():" + currentMerchant);
        return currentMerchant;
    }

    public void setCurrentMerchant(Merchants selected) {
        System.out.println("StatementByMerchantController / setCurrentMerchant() TO:" + selected);
        this.currentMerchant = selected;
        setCurrentMerchants(null);
    }

    public List<Merchants> getCurrentMerchants() {
        return currentMerchants;
    }

    public void setCurrentMerchants(List<Merchants> currentMerchants) {
        this.currentMerchants = currentMerchants;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(20) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    DataModel dm = null;

                    EntityManager em = getFacade().getEntityManager();
                    Query q = em.createNamedQuery("Statement.findByMerchant");
//                    // TODO HACK - FIX
//                    if (merchantId == null) {
//                        merchantId = "1";
//                    }
                    List<Statement> allStatementsByMerchant = new ArrayList();
                    if (getCurrentMerchants() != null) {
                        for (Merchants m : getCurrentMerchants()) {
                            q.setParameter("merchant", m.getId());
                            List<Statement> statementsByMerchant = q.getResultList();//findAll();
                            if (statementsByMerchant != null) {
                                allStatementsByMerchant.addAll(statementsByMerchant);
                            }
                        }
                    } else if (getCurrentMerchant() != null) {
                        q.setParameter("merchant", getCurrentMerchant().getId());
                        allStatementsByMerchant = q.getResultList();//findAll();
                    }

                    setTotalCost(allStatementsByMerchant);
                    dm = new ListDataModel(allStatementsByMerchant);

                    return dm;
                }
            };
        }

        return pagination;
    }

    public String prepareList() {
        recreateModel();

        return "/web/queries/queryByMerchant";
    }

    public String prepareListByMerchant() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestMap = context.getExternalContext().getRequestParameterMap();
        if (requestMap.containsKey("merchantId")) {
            // Parameter passed in from another screen 

            int merchantId = (Integer) requestMap.get("merchantId");
            setCurrentMerchant(ejbMerchantsFacade.find(merchantId));
            System.out.println("prepareListByMerchant x now - merchantId:" + merchantId);
        }
        return prepareList();
    }

    public String prepareView() {
        currentStatement = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        currentStatement = new Statement();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(currentStatement);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        currentStatement = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(currentStatement);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        currentStatement = (Statement) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(currentStatement);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("StatementDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            currentStatement = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbStatementFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbStatementFacade.findAll(), true);


    }

    @FacesConverter(forClass = Statement.class)
    public static class StatementControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            StatementByMerchantController controller = (StatementByMerchantController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "statementController");
            return controller.ejbStatementFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Statement) {
                Statement o = (Statement) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + StatementByMerchantController.class.getName());
            }
        }
    }

    /* my additions */
    private MerchantsFacade getMerchantsFacade() {
        return ejbMerchantsFacade;
    }

    /**
     * Loads new data into application.
     * 
     * @return 
     */
    public String load() throws IOException, ParseException, Exception {
        logger.debug("load() statement");
        statementLoader.load(StatementLoaderImpl.getSampleData());
        for (CCStatementCSV item : statementLoader.getDataList()) {
            Merchants merchant = (Merchants) merchantsWorker.lookupMerchant(item.getMerchant()); // qmm.getResultList().get(0);
            Categories theOneCategory = null;
            logger.debug("  Merchant text:" + item.getMerchant() + ", merchant bean:" + merchant);
            if (merchant == null) {
                //merchant = merchantsWorker.getNoMerchantMatchMerchant();
            } else {
                List<Categories> categoriesForMerchant = merchantsWorker.lookupCategoriesForMerchant(merchant);
                if (categoriesForMerchant != null) {
                    if (categoriesForMerchant.size() >= 1) {
                        theOneCategory = categoriesForMerchant.get(0);
                    } else {
                        theOneCategory = null;    // leave the edit window to present a drop-down list to let the user choose the category
                    }
                }
                logger.debug("      Category:" + theOneCategory);
            }
            logger.debug("        Create Statment bean");
            Statement statement = new Statement(item, merchant, theOneCategory);
            getFacade().create(statement);
        }

        return prepareList();
    }

    public void merchantReportCodeChanged(ValueChangeEvent e) {
        System.out.println("merchantReportCodeChanged - from:" + e.getOldValue() + ", to:" + e.getNewValue());
//       MerchantsControllerConverter converter = new MerchantsControllerConverter();
//        FacesContext context = FacesContext.getCurrentInstance();
//        Merchants newMerchant = (Merchants) converter.getAsObject(context, e.getComponent(), (String) e.getNewValue());
        setCurrentMerchant((Merchants) e.getNewValue());
        prepareListByMerchant();
    }

    public void action() {
        System.out.println("Action - Selected Merchant item: " + getCurrentMerchant());
        prepareListByMerchant();
    }

    public void action2() {
        System.out.println("Action 2 - Selected Merchant itemS: " + getCurrentMerchants());
        prepareListByMerchant();
    }
    
    public void setTotalCost(List<Statement> statements) {
        int total = 0;
        for (Statement s : statements) {
            total+=s.getAmount().intValue();
        }
        totalCost = total;
    }
    
    public int getTotalCost() {
        return this.totalCost;
    }
}
